package com.zimin.cloud.system.biz.impl;

import com.zimin.cloud.mine.pojo.system.business.DeptBO;
import com.zimin.cloud.mine.pojo.system.view.DeptVO;
import com.zimin.cloud.system.biz.IDeptBiz;
import com.zimin.cloud.system.pojo.entity.Dept;
import com.zimin.cloud.system.service.IDeptService;
import com.zimin.cloud.system.service.impl.DeptServiceImpl;
import com.zimin.common.annotation.Biz;
import com.zimin.common.enums.Number;
import com.zimin.common.utils.BeanUtils;
import com.zimin.common.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 部门 业务对象
 * </p>
 *
 * @author zimin
 * @since 2021-12-30 11:05
 */
@Biz
public class DeptBizImpl extends DeptServiceImpl implements IDeptBiz {

    @Autowired
    private IDeptService deptService;

    @Override
    public List<DeptVO> deptTree(DeptBO deptBO) {
        var deptVOList = deptService.listVO(deptBO);
        return ObjectUtils.isEmpty(deptVOList) ? deptVOList : tree(deptVOList, Number.ZERO.getStrNum());
    }

    @Override
    public boolean save(DeptBO deptBO) {
        return super.save(BeanUtils.coverClass(deptBO, Dept.class));
    }

    @Override
    public boolean updateById(DeptBO deptBO) {
        return super.updateById(BeanUtils.coverClass(deptBO, Dept.class));
    }


    /**
     * <p>获取部门树</p>
     *
     * @param deptVOList 原List
     * @param parent     上级父ID
     * @return java.util.List<com.zimin.cloud.mine.pojo.wiki.view.DeptVO>
     * @since 2021-11-24 16:55:59
     */
    private List<DeptVO> tree(List<DeptVO> deptVOList, String parent) {
        var childrenMap = deptVOList.stream()
                .collect(Collectors.groupingBy(DeptVO::getParentId));
        var children = childrenMap.get(parent);
        children.forEach(deptVO -> {
            var parentNodeId = deptVO.getId();
            var deptVOList1 = childrenMap.get(parentNodeId);
            if (ObjectUtils.isNotEmpty(deptVOList1)) {
                var tree = tree(deptVOList, parentNodeId);
                deptVO.setChildren(tree);
            }
        });
        return children;
    }


}
